package com.huilian.iotbox.data.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenqiwen
 * @CreateDate: 2022-04-11-16-30
 * @Description:
 */
public class MD5SignUtil {
    private static final String CHARSET_UTF8 = "UTF-8";
    // 兑币机APK
    public static String secret = "oFI79DZlUko!6Jr8cfR21z5&V12DizKt";
    // 烧号软件
    public static String S_H_Secret = "7DpoODxr6QYp6i0igrZMmsKBmxDBvTQl";

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
        Map<String, Object> inParams = new HashMap<>();
        inParams.put("param1", "value1");
        inParams.put("param2", "value2");

        String checkSign = MD5SignUtil.signTopRequestByMap(inParams, MD5SignUtil.S_H_Secret);
        System.out.println(checkSign);
    }

    /**
     * 签名算法
     */
    public static String signTopRequestByMap(Map<String, Object> params, String secret) throws IOException, NoSuchAlgorithmException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(secret);

        for (String key : keys) {
            Object value = params.get(key);
            if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)) {
                query.append(key).append(value);
            }
        }

        // 第三步：使用MD5/HMAC加密
        return encryptMD5Before(query, secret);
    }

    public static String signTopRequestByJsonObject(JSONObject params, String secret) throws IOException, NoSuchAlgorithmException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);
        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(secret);

        for (String key : keys) {
            Object value = params.get(key);
            if (!StringUtils.isEmpty(key) && !StringUtils.isEmpty(value)) {
                query.append(key).append(value);
            }
        }

        // 第三步：使用MD5/HMAC加密
        return encryptMD5Before(query, secret);
    }

    public static byte[] encryptHMAC(String data, String secret) throws IOException {
        byte[] bytes = null;
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(MD5SignUtil.CHARSET_UTF8), "HmacMD5");
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            bytes = mac.doFinal(data.getBytes(MD5SignUtil.CHARSET_UTF8));
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public static String encryptMD5Before(StringBuilder query, String secret) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        byte[] bytes = new byte[0];
        query.append(secret);
        bytes = encryptMD5(query.toString());

        // 第四步：把二进制转化为大写的十六进制
        return byte2hex(bytes);
    }

    public static byte[] encryptMD5(String info) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] infoBytes = info.getBytes();
        md5.update(infoBytes);
        return md5.digest();
    }

    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toLowerCase());
        }
        return sign.toString();
    }


}
